import datetime
import time

import flask_socketio

from blueprint import user
import uuid
from extension import socketio, db
from flask_socketio import emit, join_room,leave_room
from flask import Blueprint, request, jsonify
from models.models import RoomModel, UserModel, RoomUserModel

bp=Blueprint('room',__name__,url_prefix='/room')
# index界面调用
@bp.route('/create_room', methods=['POST'])
def create_room():
    room_id = str(uuid.uuid4())  # 生成唯一房间ID
    room = RoomModel(roomid=room_id)
    db.session.add(room)
    db.session.commit()
    # print(jsonify({'room_id': room_id}).json)
    return jsonify({'room_id': room_id})
# @bp.route('/joinroom', methods=['POST'])
# def joinroom():
#     data = request.json
#     print(data)
#     room_id = data.get('room_id')
#     # joinroom为库封装的方法可以创建一个Websocket房间————这里是指让当前连接的客户端加入指定房间
#     join_room(room_id)
#     user_id = data.get('user_id')
#     user = UserModel.query.get(user_id)
#     member = {"id": user_id, "name": user.username, "avatar": user.user_img}
#     print(member)
#     emit('room_info', member, room=room_id)
#     # try:
#     #     data = request.json
#     #     if not data:
#     #         return jsonify({'success': False, 'message': '请求数据为空'}), 400
#     #
#     #     room_id = data.get('room_id')
#     #     user_id = data.get('user_id')
#     #     if not room_id or not user_id:
#     #         return jsonify({'success': False, 'message': '缺少必要参数'}), 400
#     #
#     #     room = RoomModel.query.get(room_id)
#     #     if not room:
#     #         return jsonify({'success': False, 'message': '房间不存在'}), 404
#     #     player = UserModel.query.get(user_id)
#     #     if not player:
#     #         return jsonify({'success': False, 'message': '玩家不存在'}), 404
#     #
#     #     # 检查玩家是否已经加入房间
#     #     if room_userModel.query.filter_by(room_id=room_id, user_id=user_id).first():
#     #         return jsonify({'success': False, 'message': '玩家已加入房间'}), 400
#     #
#     #     # 否则将玩家加入房间
#     #     room_player = room_userModel(room_id=room_id, user_id=user_id)
#     #     db.session.add(room_player)
#     #     db.session.commit()
#     #
#     #     # 广播给房间内的所有用户
#     #     socketio.emit('player_joined', {'user_id': user_id, 'name': player.username, 'avatar': player.user_img}, room=room_id)
#     #     return jsonify({'success': True, 'message': '加入房间成功'})
#     # except Exception as e:
#     #     print(f"加入房间时发生错误: {e}")
#     #     db.session.rollback()
#     #     return jsonify({'success': False, 'message': '加入房间失败'}), 500

# WebSock监听（ROOM界面）
@socketio.on('connect')
def handle_connect():
    print('客户端已连接')

# # 广播房间信息
# def get_room_members(room_id):
#     members = RoomPlayer.query.filter_by(room_id=room_id).all()
#     return [{'player_id': member.player_id, 'name': member.player.name} for member in members]

@socketio.on('init_room')
def handle_init_room(data):
    room_id = data.get('room_id')
    # joinroom为库封装的方法可以创建一个Websocket房间————这里是指让当前连接的客户端加入指定房间
    flask_socketio.join_room(room_id)
    # 以下这段是根据中间表，找到所有房间中的人，然后通过循环返回所有人的信息
    members = RoomUserModel.query.filter_by(room_id=room_id).all()
    # members_info = [{'player_id': member.player_id, 'name': member.player.name, 'avatar': member.player.avatar} for member in members]
    if not members:
        print(f"未找到房间 {room_id} 的成员信息")
        return
    print(f"成功获取房间 {room_id} 的成员信息: {members}")
    members_info = []
    for member in members:
        user_id = member.user_id
        user = UserModel.query.get(user_id)
        members_info.append({
            'user_id': user_id,
            'name': user.username,
            'avatar': user.user_img
        })

    print(f"members_info: {members_info}")
    emit('room_info', members_info, room=room_id)

    # emit('room_info', {'members': [member]}, room=room_id)
    # emit('room_info', {'members': [member]}, room=room_id)
    # 以下这段是根据中间表，找到所有房间中的人，然后通过循环返回所有人的信息
    # members = RoomPlayer.query.filter_by(room_id=room_id).all()
    # members_info = [{'player_id': member.player_id, 'name': member.player.name, 'avatar': member.player.avatar} for member in members]





@socketio.on('join_room')
def handle_join_room(data):
    print("data:",data)
    room_id = data.get('room_id')
    # joinroom为库封装的方法可以创建一个Websocket房间————这里是指让当前连接的客户端加入指定房间
    join_room(room_id)
    user_id = data.get('user_id')
    user = UserModel.query.get(user_id)
    if user is None:
        print(f"未找到用户 ID 为 {user_id} 的用户")
        return
    member = {"user_id": user_id,"name": user.username,"avatar": user.user_img}
    # 先查询这条记录是否已经存在
    existing_record = RoomUserModel.query.filter_by(user_id=user_id, room_id=room_id).first()
    print("------------------------------------")
    print(existing_record)
    print("------------------------------------")
    if existing_record is None:
        # 插入 user_room 关联记录
        new_roomuser = RoomUserModel(user_id=user_id, room_id=room_id)
        try:
            db.session.add(new_roomuser)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(f"插入关联记录失败: {e}")
    else:
        print("关联记录已存在，无需插入")
    emit('user_joined', member, room=room_id)

    # emit('room_info', {'members': [member]}, room=room_id)
    # 以下这段是根据中间表，找到所有房间中的人，然后通过循环返回所有人的信息
    # members = RoomPlayer.query.filter_by(room_id=room_id).all()
    # members_info = [{'player_id': member.player_id, 'name': member.player.name, 'avatar': member.player.avatar} for member in members]

# WebSocket: 离开房间
@socketio.on('leave_room')
def handle_leave_room(data):
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    # 从数据库中移除用户与房间的关联记录
    existing_record = RoomUserModel.query.filter_by(user_id=user_id, room_id=room_id).first()
    if existing_record:
        try:
            db.session.delete(existing_record)
            db.session.commit()
            print("已移除")
        except Exception as e:
            db.session.rollback()
            print(f"移除关联记录失败: {e}")

    # 广播用户离开的消息
    member = {"user_id": user_id}
    emit('user_left', member, room=room_id)
    # 让用户离开 WebSocket 房间
    leave_room(room_id)
# WebSocket: 更新分数
@socketio.on('update_score')
def handle_update_score(data):
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    score = data.get('score')
    # if room_id in rooms and user_id in rooms[room_id]['scores']:
    #     rooms[room_id]['scores'][user_id] += score
    #     rooms[room_id]['history'].append({  # 记录对局历史
    #         'user_id': user_id,
    #         'score': score
    #     })
    #     # 广播更新后的房间信息
    #     socketio.emit('room_info', rooms[room_id], room=room_id)



